<?php

namespace App\Http\Utils\Integral;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Class User
 * @package App\Http\Utils\Integral
 */
class User
{
    /**
     * FAQ
     */
    const USER_BALANCE_NOT_ALLOW = "暂时不能扣除积分";

    /**
     * 平台积分发放手续费
     * @var float
     */
    private $platform = 0;

    /**
     * 平台积分发放手续费
     * @var float
     */
    private $userform = 1;

    /**
     * 用户ID
     * @var string
     */
    public $userId;

    /**
     * 商户ID
     * @var string
     */
    public $shopId;

    /**
     * 用户总积分
     * @var float
     */
    public $totalAmount = 0;

    /**
     * 是否清除累计消费
     * @var bool
     */
    private $clearCumulative = false;

    /**
     * @var array
     */
    public $flows = [];

    /**
     * User constructor.
     * @param string $userId 用户ID 【】
     * @param string $shopId 商户ID 【】
     */
    public function __construct($userId, $shopId)
    {
        $this->userId = $userId;
        $this->shopId = $shopId;
        $this->earnings();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return (string)$this->userId;
    }

    /**
     * 是否清除累计消费
     * @param array $userIds
     */
    public function clearCumulative(array $userIds, $cumulative)
    {
        $this->clearCumulative = $userIds;
        $this->cumulative = $cumulative;
    }

    /**
     * @var bool
     */
    public $day_enabled = true;

    /**
     * @var bool
     */
    public $mal_enabled = true;

    /**
     * @var bool
     */
    public $luck_enabled = true;

    /**
     * 查询用户积分
     */
    private function earnings()
    {
        $user = DB::table('user')
            ->where([
                'user_id' => $this->userId,
                'shop_id' => $this->shopId,
            ])->lockForUpdate()
            ->first();
        if (is_null($user)) {
            DB::table('user')->insert([
                'shop_id'      => $this->shopId,
                'user_id'      => $this->userId,
                'day_enabled'  => 'true',
                'mal_enabled'  => 'true',
                'luck_enabled' => 'true',
                'total_amount' => 0,
                'cumulative'   => 0,
                'create_time'  => Time::current(),
                'update_time'  => Time::current(),
            ]);
        } else {
            $this->totalAmount = $user->total_amount;
            $this->cumulative = $user->cumulative;
            $this->day_enabled = ($user->day_enabled === 'true');
            $this->mal_enabled = ($user->mal_enabled === 'true');
            $this->luck_enabled = ($user->luck_enabled === 'true');
        }
    }

    /**
     * @var int
     */
    public $recordAmount = 0;

    /**
     * 用户流水记录
     * @param string $orderNum 订单号
     * @param string $status 状态
     * @param string $reason 失败或成功描述
     * @param string $info 流水详情
     * @param float $should 应该获得的积分
     * @param int $taskId 任务ID
     * @throws \Exception
     */
    public function flow($orderNum, $status, $reason, $info, $should, $taskId = 0)
    {
        if ($should < 0) {
            throw new \Exception(self::USER_BALANCE_NOT_ALLOW, 400);
        } elseif ($should >= 0) {
            $this->flows[] = [
                'user_id'     => $this->userId,
                'shop_id'     => $this->shopId,
                'order_num'   => $orderNum,
                'status'      => $status,
                'reason'      => $reason,
                'info'        => $info,
                'refund'      => 'false',
                'integral'    => $should * $this->userform,
                'should'      => $should,
                'platform'    => $should * $this->platform,
                'history'     => $this->totalAmount + $should * $this->userform,
                'task_id'     => $taskId,
                'read'        => 'false',
                'create_time' => Time::current(),
                'update_time' => Time::current(),
            ];
            $this->totalAmount = $this->totalAmount + $should * $this->userform;
            $this->recordAmount = $this->recordAmount + $should * $this->userform;
        }
    }

    /**
     * @var int
     */
    private $cumulative = 0;

    /**
     * @param $cumulative
     */
    public function cumulative($cumulative)
    {
        $this->cumulative = $this->cumulative + $cumulative;
    }

    /**
     * 记录
     * @param bool $needPush
     */
    public function record($needPush = false)
    {
        if ($this->clearCumulative !== false) {
            DB::table('user')
                ->whereIn('user_id', $this->clearCumulative)
                ->where('shop_id', $this->shopId)
                ->update([
                    'cumulative'  => 0,
                    'update_time' => Time::current(),
                ]);
        }
        DB::table('user')
            ->where([
                'user_id' => $this->userId,
                'shop_id' => $this->shopId,
            ])->update([
                'total_amount' => $this->totalAmount,
                'cumulative'   => $this->cumulative,
                'update_time'  => Time::current(),
            ]);
        if (!empty($this->flows)) {
            DB::table('user_flow')
                ->insert($this->flows);
        }
    }
}